/*
 * 
 */

package com.spartancoder.accommodation.models;

import com.spartancoder.accommodation.beans.OptionBean;
import com.spartancoder.accommodation.db.Database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

/**
 *
 * @author andrei
 */
public class Options {

	private static Logger log = Logger.getLogger(Options.class.getName());
	private static Database db = Database.getInstance();

	public static void create( OptionBean ob ) {
		try {
			Connection conn = db.getConnection();
			String query = "insert into `options`" +
					"(`session_id`, `student_id`, `place_id`, " +
					"`status_id`, `room`, `comment`, `add_date`) values " +
					"(?, ?, ?, ?, ?, ?, now() )";
			PreparedStatement st = conn.prepareStatement(query);
			st.setInt(1, ob.getSessionId());
			st.setInt(2, ob.getStudentId());
			st.setInt(3, ob.getPlaceId());
			st.setInt(4, 1);	// Editable
			st.setInt(5, ob.getRoom());
			st.setString(6, ob.getComment());

			st.execute();

		} catch( SQLException ex ) {
			log.severe(ex.toString());
			throw new InternalError(ex.toString());
		}
	}

	public static void remove( int optionId ) {
		try {
			Connection conn = db.getConnection();
			String query = "delete from `options` where `option_id`=?";
			PreparedStatement st = conn.prepareStatement(query);
			st.setInt(1, optionId);
			st.execute();

		} catch( SQLException ex ) {
			log.severe(ex.toString());
			throw new InternalError(ex.toString());
		}
	}

	public static List<OptionBean> fetchAll( int sessionId, int studentId ) {
		try {
			Connection conn = db.getConnection();
			String query = "select * from `options` " +
					"where `session_id`=? and `student_id`=?";
			PreparedStatement st = conn.prepareStatement(query);
			st.setInt(1, sessionId);
			st.setInt(2, studentId);

			ResultSet rs = st.executeQuery();
			List<OptionBean> ret = new LinkedList<OptionBean>();
			while (rs.next()) {
				OptionBean ob = new OptionBean();
				ob.fill(rs);
				ret.add(ob);
			}
			return ret;
		} catch( SQLException ex ) {
			log.severe(ex.toString());
			throw new InternalError(ex.toString());
		}
	}
}
